package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isExclude() {
        String requestURI = request.getRequestURI();
        if(requestURI.startsWith("/member")){
            return false;
        }
        return true;
    }



    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Long userId = loadUserId();
            this.strictInsertFill(metaObject, "createBy", Long.class, userId != null ? userId : 0L);
            this.strictInsertFill(metaObject, "updateBy", Long.class, userId != null ? userId : 0L);
        } catch (Exception e) {
            // 获取用户信息失败时使用默认值
            this.strictInsertFill(metaObject, "createBy", Long.class, 0L);
            this.strictInsertFill(metaObject, "updateBy", Long.class, 0L);
        }

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            Long userId = loadUserId();
            this.strictUpdateFill(metaObject, "updateBy", Long.class, userId != null ? userId : 0L);
        } catch (Exception e) {
            this.strictUpdateFill(metaObject, "updateBy", Long.class, 0L);
        }

        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    private Long loadUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            return loginUser != null ? loginUser.getUserId() : null;
        } catch (Exception e) {
            return null;
        }
    }
}
